<template>
    <div>
        <van-nav-bar
  title="标题"
  left-text="返回"
 
  left-arrow
  @click-left="onClickLeft"

/>
        <van-search
        v-model="SearchContent"
            placeholder="请输入搜索关键词"
            input-align="center"
            @search="search"
/>           
        <div class="historybox" v-if="this.historyData.length">
            <van-tag v-for="(item , index) in historyData" :key="item" closeable size="medium" type="primary" @close="close(index)" @click="search(item)">
                {{item}}
        </van-tag>
        </div>
        <div class="" v-else>
            暂无数据
        </div>

    </div>
</template>

<script>

import {Tag} from'vant'
    export default {
            data(){
                return{
                    SearchContent:"",//查找的的关键字
                    historyData:[]//查找的历史纪录
                }
            },
            created(){
                //获取查找的历史纪录
                this.historyData=localStorage.getItem('historyData')?JSON.parse(localStorage.getItem('historyData')):[]
          
            },
            methods:{
                search(val){
                    //将查找的关键字保存在数组内并放入缓存里
                    this.historyData.push(val)
                    this.historyData = [...new Set(this.historyData)]
                    console.log(this.historyData);
                    //判断输入框的内容是否为空
                    if(val){

                        localStorage.setItem('historyData',JSON.stringify(this.historyData))
                        //跳转到搜索的列表页
                        this.$router.push('/searchdata?key='+val)
                    }
                    
                        
                
                },
                onClickLeft(){
                    this.$router.go(-1)
                },
                //删除历史纪录
                close(index){
                    this.historyData.splice(index,1)
                    if(this.historyData.length===0){
                       localStorage.setItem('historyData',JSON.stringify(this.historyData)) 
                    }else{
                        localStorage.removeItem('historyData')
                    }
                     
                },
                //点击历史纪录 查找点击的内容
                search(item){

                     this.historyData.unshift(item)
                    this.historyData = [...new Set(this.historyData)]
                    console.log(this.historyData);
                    if(item){
                        localStorage.setItem('historyData',JSON.stringify(this.historyData))
                        this.$router.push('/searchdata?key='+item)
                    }
                }
            }
    }
</script>

<style lang="scss" scoped>
.historybox{
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
}
.historybox>*{
    margin: 5px 10px;
}
</style>